<template>
  <view>
    <u-form :model="form" ref="uForm" style="margin: 0 20rpx;">
      <u-form-item label-width="145"  label="*课程名称" prop="name">
        <u-input placeholder="可输入1~10个字符" v-model="form.name" />
      </u-form-item>
      <u-form-item label-width="200"  label="*最大加入人数" prop="maxJoinCount">
        <u-input placeholder="可输入1~200的数字" v-model="form.maxJoinCount" />
      </u-form-item>
    </u-form>
    <view class="btn">
      <u-button size="medium" shape="circle" type="primary" @click="submit " :ripple="true" ripple-bg-color="#a0cfff">提交</u-button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        name: '',
        maxJoinCount: 200,
        userId: ''
      },
      isDisabled: false,
      rules: {
        name: [
          {
            min: 1,
            max: 10,
            type: "string",
            required: true,
            message: '课程名可输入1~10个字符',
            trigger: 'blur'
          }
        ],
        maxJoinCount: [
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return (value <= 200 && value >= 1);
            },
            type: "integer",
            required: true,
            message: '只可输入1~200的数字',
            trigger: 'blur'
          }
        ]
      }
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(){
    uni.$emit("setVuexUserInfo",{user:null,isLoginPage: false});
  },
  methods:{
    submit(){
      this.form.userId = this.$store.state.user.id;
      if(this.form.userId === null || this.form.userId === ''){
        return;
      }
      this.$refs.uForm.validate(valid => {
        if (valid) {
          this.$u.api.createCourse(this.form).then(resp => {
            this.$u.toast("创建成功！");
            uni.$emit("indexInitial");
            setTimeout(() => {
              uni.switchTab({
                url:'/pages/index/index',
                fail: (err) => {
                  this.$u.toast('跳转出错');
                }
              })
            },1000)
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
.btn{
  text-align: center;
  margin-top: 20rpx;
  margin-bottom: 30rpx
}
</style>
